package com.lemon.cloud.redisson.lock;

import com.lemon.cloud.lock.AbstractDistributedLock;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.util.Assert;

import java.util.concurrent.TimeUnit;

/**
 * @author lemon
 * @version 1.0
 * @description: Redisson实现分布式锁
 * @date Create by lemon on 2019-09-08 20:47
 */
@Slf4j
@ConditionalOnClass(RedissonClient.class)
public class RedissonDistributedLock extends AbstractDistributedLock {
    @Setter
    @Getter
    private RedissonClient redissonClient;

    /**
     * @param key
     * @param expireTime
     * @param expireTimeUnit
     * @return boolean
     * @description
     * @author lemon
     * @date 2019-09-08 20:26
     */
    @Override
    protected boolean acquire(String key, long expireTime, TimeUnit expireTimeUnit) {
        RLock lock = redissonClient.getLock(key);

        try {
            return lock.tryLock(expireTime, expireTimeUnit);
        } catch (Exception e) {
            log.error("Obtaining an exception for the redisson distributed lock", e);
            return false;
        }
    }

    /**
     * @param key key值
     * @return void
     * @description 释放锁
     * @author lemon
     * @date 2019-09-04 12:49
     */
    @Override
    public boolean unlock(String key) {
        try {
            RLock lock = redissonClient.getLock(key);
            lock.unlock();
            return true;
        } catch (Exception e) {
            log.error("Release redisson lock occured an exception", e);
            return false;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Assert.state(this.getRedissonClient() != null, "RedissonClient is required");
    }
}
